package com.github.niefy.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.niefy.modules.sys.dao.SysAddressDao;
import com.github.niefy.modules.sys.entity.SysAddressEntity;
import com.github.niefy.modules.sys.service.SysAddressService;
import com.github.niefy.modules.wx.entity.WxUser;
import com.github.niefy.modules.wx.service.WxUserService;
import com.github.niefy.qrcode.AddressCodeUtils;
import com.github.niefy.qrcode.MatrixToBgImageConfig;
import com.google.gson.JsonObject;
import me.chanjar.weixin.common.enums.WxType;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import me.chanjar.weixin.mp.bean.tag.WxUserTag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static me.chanjar.weixin.mp.enums.WxMpApiUrl.UserTag.TAGS_DELETE;


@Service("sysAddressService")
public class SysAddressServiceImpl extends ServiceImpl<SysAddressDao, SysAddressEntity> implements SysAddressService {
    @Autowired
    private WxMpService wxService;

    @Autowired
    @Lazy
    private WxUserService wxUserService;

    @Override
    public List<SysAddressEntity> queryPage(Map<String, Object> params) {
        String appid = (String) params.get("appid");
        List<SysAddressEntity> list = this.list(
                new QueryWrapper<SysAddressEntity>().eq(StringUtils.hasText(appid), "appid", appid)
        );

        return list;
    }

    @Override
    public SysAddressEntity createQrCode(SysAddressEntity entity) throws WxErrorException {
        WxMpQrCodeTicket ticket;
        ticket = wxService.getQrcodeService().qrCodeCreateLastTicket(entity.getId().toString());

        entity.setSceneStr(entity.getId().toString());
        entity.setTicket(ticket.getTicket());
        entity.setUrl(ticket.getUrl());

        //带海报的二维码生成
        //获取小区+楼号+单元名称
        String addressName = entity.getName();
        SysAddressEntity tempEntity = entity;
        while (tempEntity != null && tempEntity.getParentId() != 0 && tempEntity.getParentId() != null) {
            tempEntity = this.getById(tempEntity.getParentId());
            addressName = tempEntity.getName() + addressName;
        }

        //设定二维码生成参数
        MatrixToBgImageConfig config = new MatrixToBgImageConfig();
        config.setQrcode_url(entity.getUrl());
        config.setDevice_code(addressName);
        config.setFontSize(100);
        config.setBgFile("qrtemplate/bg1.png");
        //生成二维码,上传云存储，保存url
        entity.setTemplateUrl(AddressCodeUtils.createQrcode(config));

        return entity;
    }

    @Override
    public SysAddressEntity queryByTagid(String tagid) {
        return this.getOne(
                new QueryWrapper<SysAddressEntity>().eq(StringUtils.hasText(tagid), "tag_id", tagid)
        );
    }

    @Override
    public SysAddressEntity creatTag(String appid, SysAddressEntity sysAddress) throws WxErrorException, UnsupportedEncodingException {
        wxService.switchoverTo(appid);
        //获取小区+楼号+单元名称
        String addressName = sysAddress.getName();
        SysAddressEntity tempEntity = sysAddress;
        while (tempEntity != null && tempEntity.getParentId() != 0 && tempEntity.getParentId() != null) {
            tempEntity = this.getById(tempEntity.getParentId());
            addressName = tempEntity.getName() + addressName;
        }
        WxUserTag wxUserTag = wxService.getUserTagService().tagCreate(addressName);
        sysAddress.setTagId(Math.toIntExact(wxUserTag.getId()));
        sysAddress.setTagName(wxUserTag.getName());
        return sysAddress;
    }

    @Override
    public SysAddressEntity updateTag(String appid, SysAddressEntity sysAddress) throws WxErrorException {
        wxService.switchoverTo(appid);
        //获取小区+楼号+单元名称
        String addressName = sysAddress.getName();
        SysAddressEntity tempEntity = sysAddress;
        while (tempEntity != null && tempEntity.getParentId() != 0 && tempEntity.getParentId() != null) {
            tempEntity = this.getById(tempEntity.getParentId());
            addressName = tempEntity.getName() + addressName;
        }
        wxService.getUserTagService().tagUpdate((long) sysAddress.getTagId(), addressName);
        sysAddress.setTagName(addressName);
        return sysAddress;
    }

    @Override
    public int deleteTag(String appid, Long[] ids) throws WxErrorException {
        wxService.switchoverTo(appid);
        List<WxUser> wxUsers = wxUserService.getUserList();
        List<Long> tagids = new ArrayList<>();
        for (Long id : ids) {
            SysAddressEntity address = this.getById(id);
            if (0 != this.list(new QueryWrapper<SysAddressEntity>().eq(true, "parent_id", address.getId())).size()) {
                return 1;
            }
            for (WxUser wxUser : wxUsers) {
                for (Object selectTagid : wxUser.getTagidList()) {
                    if (Long.valueOf(String.valueOf(selectTagid)).longValue() == address.getTagId()) {
                        return 2;
                    }
                }
            }
            tagids.add((long) address.getTagId());
        }
        for (Long tagid : tagids) {
            wxService.getUserTagService().tagDelete(tagid);
        }
        return 0;
    }

}